let todoList = [];
const addBtn = document.getElementById("todo-add");
const inputEle = document.getElementById("todo-input");
const todoListEle = document.getElementById("todo-list");

/**
 * 添加待办事项
 */
function addTodoItem() {
  const inputValue = inputEle.value.trim();
  if (inputValue !== "") {
    const newItem = {
      id: Math.floor(Date.now()),
      title: inputValue,
      completed: false,
    };

    todoList.push(newItem);
    render(newItem);
  }
}

/**
 * 添加待办事件元素
 *
 * @param {object} newItem 待办事件对象
 */
function render(newItem) {
  const liEle = document.createElement("li");
  liEle.className = "todo-item-li";
  liEle.setAttribute("data-id", newItem.id);

  const checkboxEle = document.createElement("input");
  checkboxEle.type = "checkbox";
  checkboxEle.className = "todo-item-checkbox";
  checkboxEle.setAttribute("data-id", newItem.id);
  checkboxEle.addEventListener("change", handleCheckChange);

  const textEle = document.createElement("span");
  textEle.className = "todo-item-text";
  textEle.innerText = newItem.title;
  textEle.setAttribute("data-id", newItem.id);

  const closeBtnEle = document.createElement("button");
  closeBtnEle.innerText = "删除";
  closeBtnEle.setAttribute("data-id", newItem.id);
  closeBtnEle.addEventListener("click", removeTodo);

  liEle.appendChild(checkboxEle);
  liEle.appendChild(textEle);
  liEle.appendChild(closeBtnEle);
  todoListEle.appendChild(liEle);
}

/**
 * 删除事件
 *
 * @param {object} e 事件对象
 */
function removeTodo(e) {
  const targetId = e.target.getAttribute("data-id");
  todoList = todoList.filter((item) => item.id !== targetId);
  const todoItemEles = document.querySelectorAll(".todo-item-li");
console.log('todoItemEles', todoItemEles);

  let removeEle;
  for (const item of todoItemEles) {
    if (item.getAttribute("data-id") === targetId) {
      removeEle = item;
      break;
    }
  }
  removeEle?.remove();
}

/**
 * 选中变化事件
 *
 * @param {object} e 事件对象
 * @returns null
 */
function handleCheckChange(e) {
  const targetId = e.target.getAttribute("data-id");
  const todoTextEles = document.querySelectorAll(".todo-item-text");
  let targetTextEle;

  for (const item of todoTextEles) {
    if (item.getAttribute("data-id") === targetId) {
      targetTextEle = item;
      break;
    }
  }

  if (e.target.checked) {
    targetTextEle.classList.add("done");
    return;
  }

  targetTextEle.classList.remove("done");
}

addBtn.addEventListener("click", addTodoItem);
